<template>
  <div class="mod-prod-sku-tag">
    <el-form-item label="商品规格">
      <el-button size="mini" @click="showSpecsSelect()">添加规格</el-button>
      <div v-for="(pp, ppIndex) in skuPropertiesList" :key="ppIndex">
        <span>{{pp.specsName}}</span>
        <el-button class="button-new-tag" type="text"  icon="el-icon-delete" @click="removeSpecs(ppIndex)">删除</el-button>
        <br/>
        <el-tag v-for="(specsValue, vIndex) in pp.specsValueList" :key="vIndex" closable @close="handleRemoveSpecsValue(ppIndex, vIndex)">
          {{specsValue}}
        </el-tag>

        <el-input v-if="specsItemInputs[ppIndex] && specsItemInputs[ppIndex].visible" class="input-new-tag" size="small"
          v-model="specsItemInputs[ppIndex].value" :ref="`saveSpecsInput${ppIndex}`"
          @keyup.enter.native="handleInputConfirm(ppIndex)" @blur="handleInputConfirm(ppIndex)"/>
        <el-button v-else class="button-new-tag" icon="el-icon-plus" size="small" @click="showSpecsValueInput(ppIndex)">添加</el-button>
      </div>
    </el-form-item>

    <el-form-item label="规格名" v-show="isShowSpecsSelect">
      <el-col :span="8">
        <el-select v-model="addSpecsSelect.specsName" filterable allow-create default-first-option @change="handleSpecsChange" style="width: 100%;">
          <el-option v-for="item in unUseSpecsList"  :key="item.id" :value="item.specsName">{{item.specsName}}</el-option>
        </el-select>
      </el-col>
    </el-form-item>
    <el-form-item label="规格值" v-show="isShowSpecsSelect">
      <el-col :span="8">
        <el-select v-model="addSpecsSelect.selectValues" multiple filterable allow-create default-first-option style="width: 100%;">
          <el-option v-for="item in dbSpecsValues" :key="item.id" :value="item.specsValue">{{item.specsValue}}</el-option>
        </el-select>
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button size="mini" type="primary" @click="addSpecs()" v-show="isShowSpecsSelect">确定</el-button>
      <el-button size="mini" @click="hideSpecsSelect()" v-show="isShowSpecsSelect">取消</el-button>
    </el-form-item>

  </div>
</template>

<script>
export default {
  name:'SkuProperties',
  props: {
    skuPropertiesList: {
      default: []
    },
  },
  data () {
    return {
      isShowSpecsSelect: false,
      addSpecsSelect: {
        specsName: '',
        selectValues: []
      },
      specsItemInputs: [],
      skuList:[],
      // 数据库中的规格
      dbSpecsList: [],
      // 根据选定的规格所查询出来的规格值
      dbSpecsValues: [],
    }
  },
  created: function () {
    this.$httpGet('mall/prodSpecs/listAll').then(({data}) => {
      this.dbSpecsList = data
    })
  },
  computed: {
    // 未使用的规格, 通过计算属性计算
    unUseSpecsList () {
      let res = []
      this.dbSpecsList.forEach(t=>{
        if(!this.skuPropertiesList.find(pp => pp.specsName === t.specsName)){
          res.push(t)
        }
      });
      return res;
    },
    defalutSku () {
      return this.$store.state.prod.defalutSku
    }
  },
  methods: {
    // 显示规格名、规格值输入框
    showSpecsSelect () {
      this.isShowSpecsSelect = !this.isShowSpecsSelect
    },
    // 隐藏规格名、规格值输入框
    hideSpecsSelect () {
      this.isShowSpecsSelect = false
      this.clearSpecsSelect()
    },
    addSpecs () {
      if (!this.addSpecsSelect.specsName) {
        this.$message.error('请选择规格')
        return
      }
      let selectValues = this.addSpecsSelect.selectValues
      if (!selectValues.length) {
        this.$message.error('请选择规格值')
        return
      }
      this.skuPropertiesList.push({ specsName: this.addSpecsSelect.specsName, specsValueList: selectValues });
      this.isShowSpecsSelect = false
      // 添加规格 后计算
      this.calcSpecsSkuList(1, this.skuPropertiesList.length-1);
      this.emitChange();
      this.clearSpecsSelect()
    },
    // 清除规格值输入框内容
    clearSpecsSelect () {
      this.addSpecsSelect = { specsName: '', selectValues: [] }
      this.dbSpecsValues = []
    },
      // 规格名输入框，选中规格事件
    handleSpecsChange () {
        // 清空规格值输入框
      this.dbSpecsValues = []
      this.addSpecsSelect.selectValues = []
        // 判断规格名输入的值是否为数据库中已有的值
      let specs = this.dbSpecsList.find(spec => spec.specsName === this.addSpecsSelect.specsName)
        // 如果不是，则说明为用户随便输入
      if (!specs) return
        // 如果数据库已有该规格名，则获取根据id获取该规格名称含有的规格值
      this.$httpGet('mall/prodSpecs/listSpecValue/'+specs.id).then(({data}) => {
        this.dbSpecsValues = data
      });
    },

    // 关闭标签 --删除
    handleRemoveSpecsValue (ppIndex, ppValueIndex) {
      let specsValue = this.skuPropertiesList[ppIndex].specsValueList[ppValueIndex];
      this.skuPropertiesList[ppIndex].specsValueList.splice(ppValueIndex, 1)
      // 删除规格值 后计算
      this.calcSpecsSkuList(4, ppIndex, ppValueIndex, specsValue);
      this.emitChange();
    },
    // 标签输入框确定时调用
    handleInputConfirm (ppIndex) {
      let newSpecsValue = this.specsItemInputs[ppIndex].value
      if (!newSpecsValue) {
        this.specsItemInputs[ppIndex].visible = false
        this.specsItemInputs[ppIndex].value = ''
        return ;
      }

      let specsValueList = this.skuPropertiesList[ppIndex].specsValueList;
      if(!specsValueList){
        specsValueList = [];
      }
      // 新增规格值时，判断是否存在同名的规格值
      if(specsValueList.indexOf(newSpecsValue) > -1){
        this.$message.error(newSpecsValue+'已存在')
        return
      }

      specsValueList.push(newSpecsValue);
      this.skuPropertiesList[ppIndex].specsValueList = specsValueList;
      // 添加规格值 后计算
      this.calcSpecsSkuList(2, ppIndex, specsValueList.length-1, newSpecsValue);
      this.emitChange();

      this.specsItemInputs[ppIndex].visible = false
      this.specsItemInputs[ppIndex].value = ''
    },
    // 显示标签输入框
    showSpecsValueInput (ppIndex) {
      this.specsItemInputs.push({ visible: false, value: '' })
      this.specsItemInputs[ppIndex].visible = true
      this.$nextTick(() => {
        this.$refs[`saveSpecsInput${ppIndex}`][0].$refs.input.focus()
      })
    },
    // 删除 规格
    removeSpecs (ppIndex) {
      this.skuPropertiesList.splice(ppIndex, 1);
      // 删除规格的计算
      this.calcSpecsSkuList(3, ppIndex);
      this.emitChange();
    },

    calcSpecsSkuList(type, ppIndex, ppValueIndex, specsValue){
      let skuList = []
      if (type === 4) { // 删除规格值
        this.skuList.forEach(sku => {
          if(sku.propertiesList[ppIndex].specsValue != specsValue){
            skuList.push(sku)
          }
        })
        this.skuList = skuList;
        return;
      }

      if (type === 2) {// 添加规格值
      debugger
        if(this.skuPropertiesList.length == 1){
          let sku = JSON.parse(JSON.stringify(this.skuList[0]));
          sku.propertiesList[ppIndex].specsValue = specsValue;
          sku.skuName = specsValue;
          this.skuList.push(sku);
        }else{
          this.skuPropertiesList.forEach((pp, index)=>{
            if(index != ppIndex){
              pp.specsValueList.forEach(sv=>{
                let sku = JSON.parse(JSON.stringify(this.skuList[0]));
                sku.propertiesList[index].specsValue = sv;
                sku.propertiesList[ppIndex].specsValue = specsValue;
                let skuNameArr = sku.skuName.split(' ');
                skuNameArr[index] = sv;
                skuNameArr[ppIndex] = specsValue;
                sku.skuName = skuNameArr.join(' ');
                this.skuList.push(sku);
              });
            }
          });
        }
        return;
      }

      // 增加或删除规格
      this.skuList = [];
      // 没有规格的时候
      if(this.skuPropertiesList.length == 0){
        let sku = JSON.parse(JSON.stringify(this.defalutSku));
        sku.skuName = "";
        this.skuList.push(sku);
        return;
      }

      let skuArray = [];
      let ppList = [];
      this.skuPropertiesList.forEach((pp, index)=>{
        if(skuArray.length==0){
          skuArray = [...pp.specsValueList];
          pp.specsValueList.forEach(v=>ppList.push([{specsName: pp.specsName, specsValue: v}]));
        }else{
          let tempArr = [];
          let tempPpList = [];
          skuArray.forEach(item=>{
            pp.specsValueList.forEach(sv=>{
              tempArr.push(item + " " + sv);
            });
          });
          ppList.forEach(spArr=>{
            pp.specsValueList.forEach(sv=>{
              let arr = [...spArr];
              arr.push({specsName: pp.specsName, specsValue: sv})
              tempPpList.push(arr);
            });
          })
          skuArray = tempArr;
          ppList = tempPpList;
        }
      });
      skuArray.forEach((item, index)=>{
        let sku = Object.assign({}, this.defalutSku)
        sku.skuName = item;
        sku.propertiesList = ppList[index];
        this.skuList.push(sku);
      })
    },

    emitChange(){
      this.$emit("change", this.skuPropertiesList, this.skuList);
    },
  }
}
</script>

<style lang="scss">
.mod-prod-sku-tag {
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
}

// 新增规格外部边框
.sku-border{
  border: 1px solid #EBEEF5;
  width:70%
}
.sku-background{
  background-color: #F6f6f6;
  margin: 12px 12px;
  .el-button{
    margin-left: 10px;
    span{
      color:#000 !important;
    }
  }
  .el-form-item__label{
    padding:0 24px 0 0
  }
}
.sku-tag{
  margin: 12px 12px;
}
.tagTree{
  margin-left: 18px;
  padding-bottom:8px;
}
</style>
